package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.LineUp;
import com.tianxin.workbao.workBao.bean.LineUpDao;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.exception.OkHttpException;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.BeansUtil;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;
import com.tianxin.workbao.workBao.utils.common.SPUtils;

import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.WhereCondition;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hacker on 2017/6/22.
 */

public class LineUpProvide extends BaseDataProvide {
    private Integer mTag;
    private Integer mPage = 1;
    private UpdateListViewListener mUpdateListViewListener;
    private boolean isGetData = true;
    private boolean isDeleteData = false;
    private List<LineUp> mLineUps;
    private LineUpDao lineUpDao;


    public LineUpProvide(Context context, UpdateListViewListener listener, Integer tag) {
        super(context);
        this.mTag = tag;
        mContext = context;
        mUpdateListViewListener = listener;
        lineUpDao = mGreenDaoHelper.getDaoSession().getLineUpDao();
    }


    public void getLineups(int page) {
        this.mPage = page;
        isGetData = true;
        if (NetworkUtils.isConnected(mContext)) {
            getFromServer();
        } else {
            getFromDb();
            refreshUI();
        }
    }

    private void getFromServer() {
        mUpdateListViewListener.showProgress();
        Map<String, String> map = new HashMap<>();
        map.put(Constant.APPTOKEN_NAME, getAppToken());
        map.put("tag", mTag + "");
        map.put("page", mPage + "");
        map.put("userid", SPUtils.getPrefLong(Constant.CURRENT_USER_ID, 0) + "");
        RequestParams params = new RequestParams(map);
        CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getLineUpUrl(), params), getDisposeDataHandle());
    }

    public void getFromDb() {
        Query query = null;
        switch (mTag) {
            case 0:
                query = lineUpDao.queryBuilder()
                        .where(LineUpDao.Properties.Isloadcar.eq(0))
                        .where(LineUpDao.Properties.Status.gt(0))
                        .offset((mPage - 1) * Constant.LOAD_CAR_PAGE_SIZE)
                        .limit(Constant.LOAD_CAR_PAGE_SIZE)
                        .build();
                break;
            case 1:
                query = lineUpDao.queryBuilder()
                        .where(LineUpDao.Properties.Isloadcar.eq(1))
                        .where(LineUpDao.Properties.Status.gt(0))
                        .offset((mPage - 1) * Constant.LOAD_CAR_PAGE_SIZE)
                        .limit(Constant.LOAD_CAR_PAGE_SIZE)
                        .orderDesc(LineUpDao.Properties.Addtime)
                        .build();
                break;
            case 2:
                long loaderUserId = SPUtils.getPrefLong(Constant.CURRENT_USER_ID, 0);
                query = lineUpDao.queryBuilder()
                        .where(LineUpDao.Properties.Isloadcar.eq(1))
                        .where(LineUpDao.Properties.Status.gt(0))
                        .where(LineUpDao.Properties.Loaduserid.eq(loaderUserId))
                        .offset((mPage - 1) * Constant.LOAD_CAR_PAGE_SIZE)
                        .limit(Constant.LOAD_CAR_PAGE_SIZE)
                        .orderDesc(LineUpDao.Properties.Addtime)
                        .build();
                break;
        }
        mLineUps = query.list();
    }


    /**
     * 保存到数据中
     *
     * @param obj 请求返回的所有内容
     */
    private void saveToDb(Object obj) {
        if (obj instanceof List) {
            for (int i = 0; i < mLineUps.size(); i++) {
                lineUpDao.insertOrReplace(mLineUps.get(i));
            }
        } else {
            lineUpDao.insertOrReplace((LineUp) obj);
        }
    }

    @Override
    public DisposeDataHandle getDisposeDataHandle() {
        disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        disposeDataListener = new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                mUpdateListViewListener.hideProgress();
                try {
                    JSONObject object = new JSONObject(responseObj.toString());
                    int status = object.getInt(Constant.RESPONSE_STATUS);
                    String information = object.getString(Constant.RESPONSE_INFO);
                    if (status > 0) {
                        if (isGetData == false || isDeleteData == true) {
                            mUpdateListViewListener.showMessage("ok");
                            return;
                        }
                        String dataJson = object.getString(Constant.RESPONSE_DATA);
                        if (mLineUps != null && !mLineUps.isEmpty()) {
                            mLineUps.clear();
                        }
                        if (dataJson != null || dataJson.length() > 2) {
                            try {
                                if (dataJson.startsWith("[") && dataJson.endsWith("]") && dataJson.length() > 3) {
                                    mLineUps = BeansUtil.lineUpToBeans(dataJson);
                                    refreshUI();
                                    saveToDb(mLineUps);
                                } else {
                                    LineUp lineUp = BeansUtil.lineUpToBean(dataJson);
                                    mLineUps.add(lineUp);
                                    refreshUI();
                                    saveToDb(mLineUps);
                                }
                            } catch (Exception e) {
                                mUpdateListViewListener.showMessage("mLineUps To Bean Error :类型转换出错" + e.getMessage());
                            }

                        } else {
                            mUpdateListViewListener.showMessage(information);
                        }
                    } else {
                        if (isGetData == false || isDeleteData == true) {
                            mUpdateListViewListener.showMessage("failure" + information);
                        } else {
                            mUpdateListViewListener.showMessage(information);
                        }
                        if (mLineUps != null && !mLineUps.isEmpty()) {
                            mLineUps.clear();
                        }
                        refreshUI();
                    }

                } catch (JSONException e) {
                    showRequestErrorMessage(mUpdateListViewListener, responseObj.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                mUpdateListViewListener.hideProgress();
                if (reasonObj instanceof OkHttpException) {
                    OkHttpException exception = (OkHttpException) reasonObj;
                    mUpdateListViewListener.showMessage(exception.getEcode() + ":" + exception.getEmsg().toString());
                } else {
                    showRequestErrorMessage(mUpdateListViewListener, reasonObj.toString());
                }
            }
        };
        return disposeDataListener;
    }

    @Override
    public void refreshUI() {
        if (mPage > 1) {
            mUpdateListViewListener.onLoadMoreData(mLineUps);
        } else {
            mUpdateListViewListener.onRefreshData(mLineUps);
        }
    }

    public void saveLoadCarInfo(LineUp lineUp) {
        isGetData = false;
        if (NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showProgress();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("lineup", JSON.toJSONString(lineUp));
            RequestParams params = new RequestParams(map);
            CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getsaveLineUpUrl(), params), getDisposeDataHandle());
        } else {
            mUpdateListViewListener.showMessage(
                    mContext.getResources().getString(R.string.poor_network));
        }
    }

    public void checkFree(Long id) {
        isGetData = false;
        if (NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showProgress();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("id", id + "");
            RequestParams params = new RequestParams(map);
            CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getcheckLineUpUrl(), params), getDisposeDataHandle());
        } else {
            mUpdateListViewListener.showMessage("failure" +
                    mContext.getResources().getString(R.string.poor_network));
        }
    }

    public void search(String query) {
        if (mLineUps != null) {
            mLineUps.clear();
            mPage = 1;
        }
        String where = "";
        if (query.length() > 2) {
            where = "carnumber like '%" + query + "%'";
        } else {
            mUpdateListViewListener.showMessage("输入有错！");
        }
        if (where.length() < 1) return;
        Query<LineUp> lineUpQuery = null;
        lineUpQuery = lineUpDao.queryBuilder()
                .where(new WhereCondition.StringCondition(where))
                .orderAsc(LineUpDao.Properties.Isloadcar)
                .orderDesc(LineUpDao.Properties.Addtime)
                .build();
        mLineUps = lineUpQuery.list();
        refreshUI();
    }
}
